import { refreshToken } from '@/api/user'

let isRefreshing = false
let subscribers = []

// 添加订阅者
function addSubscriber(callback) {
  subscribers.push(callback)
}

// 执行所有订阅者
function onRefreshed(token) {
  subscribers.forEach(callback => callback(token))
  subscribers = []
}

// 刷新 token
export function refreshTokenRequest() {
  if (isRefreshing) {
    return new Promise(resolve => {
      addSubscriber(token => {
        resolve(token)
      })
    })
  }
  
  isRefreshing = true
  
  return new Promise((resolve, reject) => {
    refreshToken().then(response => {
      const newToken = response.jwt
      if (newToken) {
        localStorage.setItem('jwt', newToken)
        onRefreshed(newToken)
        resolve(newToken)
      } else {
        reject(new Error('刷新 token 失败'))
      }
    }).catch(error => {
      reject(error)
    }).finally(() => {
      isRefreshing = false
    })
  })
}

// 定时刷新 token (每25分钟)
export function startTokenRefreshTimer() {
  setInterval(() => {
    const token = localStorage.getItem('jwt')
    if (token) {
      refreshTokenRequest().catch(error => {
        console.error('自动刷新 token 失败:', error)
      })
    }
  }, 25 * 60 * 1000) // 25分钟
}